#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
RAG岗位推荐API演示

直接演示API功能，不依赖Django服务器
"""

import json
import os
import tempfile
from typing import Dict, Any

def simulate_resume_upload_and_recommend(resume_content: str, top_n: int = 10) -> Dict[str, Any]:
    """
    模拟简历上传和RAG推荐流程
    
    Args:
        resume_content: 简历文本内容
        top_n: 推荐岗位数量
        
    Returns:
        Dict: API响应格式的推荐结果
    """
    
    print("🚀 开始RAG推荐流程...")
    print(f"📄 简历内容长度: {len(resume_content)} 字符")
    print(f"🎯 请求推荐岗位: {top_n} 个")
    
    # 1. 模拟简历解析
    print("\n📊 Step 1: 解析简历内容...")
    resume_analysis = parse_resume_mock(resume_content)
    print(f"   ✅ 提取技能: {len(resume_analysis['skills'])} 项")
    print(f"   ✅ 工作经验: {resume_analysis['experience_years']} 年")
    
    # 2. 模拟RAG检索
    print("\n🔍 Step 2: 执行混合检索...")
    print("   🔄 ES关键词检索...")
    es_results = simulate_es_search(resume_analysis)
    print(f"   ✅ ES检索结果: {len(es_results)} 个")
    
    print("   🔄 Milvus语义检索...")
    milvus_results = simulate_milvus_search(resume_analysis)
    print(f"   ✅ Milvus检索结果: {len(milvus_results)} 个")
    
    # 3. 模拟结果融合
    print("\n🔄 Step 3: 融合检索结果...")
    fused_results = fuse_search_results(es_results, milvus_results, top_n)
    print(f"   ✅ 融合后岗位: {len(fused_results)} 个")
    
    # 4. 模拟LLM推荐理由生成
    print("\n🤖 Step 4: 生成推荐理由...")
    for job in fused_results:
        job['match_reason'] = generate_match_reason_mock(resume_analysis, job)
    print("   ✅ 推荐理由生成完成")
    
    # 5. 构建API响应
    api_response = {
        'success': True,
        'message': f'RAG推荐成功，共推荐{len(fused_results)}个岗位',
        'data': {
            'resume_info': {
                'file_name': 'demo_resume.txt',
                'skills': resume_analysis['skills'],
                'experience_years': resume_analysis['experience_years'],
                'education': resume_analysis['education'],
                'location': resume_analysis['location'],
                'parsing_time': 1.2
            },
            'job_recommendations': fused_results,
            'recommendation_summary': {
                'total_recommendations': len(fused_results),
                'avg_match_score': round(sum(job['match_score'] for job in fused_results) / len(fused_results), 3),
                'top_skills_matched': resume_analysis['skills'][:5],
                'search_methods_used': ['ES关键词检索', 'Milvus语义检索', '混合结果融合'],
                'es_results_count': len(es_results),
                'milvus_results_count': len(milvus_results)
            }
        }
    }
    
    print("\n✅ RAG推荐流程完成!")
    return api_response

def parse_resume_mock(content: str) -> Dict[str, Any]:
    """模拟简历解析"""
    import re
    
    # 提取技能
    skills = []
    skill_keywords = [
        'Python', 'Java', 'JavaScript', 'React', 'Vue', 'Django', 
        'Spring', 'MySQL', 'Redis', 'Docker', 'Kubernetes', 'Git',
        'Spark', 'Hadoop', 'TensorFlow', 'PyTorch', 'AWS', 'Azure'
    ]
    
    content_lower = content.lower()
    for skill in skill_keywords:
        if skill.lower() in content_lower:
            skills.append(skill)
    
    # 提取经验年限
    exp_match = re.search(r'(\d+)\s*年.*?经验|经验.*?(\d+)\s*年', content)
    experience_years = int(exp_match.group(1) or exp_match.group(2)) if exp_match else 0
    
    # 提取教育背景
    education = '本科' if '本科' in content else '未识别'
    
    # 提取地点
    cities = ['北京', '上海', '深圳', '广州', '杭州']
    location = next((city for city in cities if city in content), '未识别')
    
    return {
        'skills': skills,
        'experience_years': experience_years,
        'education': education,
        'location': location
    }

def simulate_es_search(resume_analysis: Dict[str, Any]) -> list:
    """模拟ES关键词检索"""
    
    # 基于技能匹配的模拟岗位
    es_jobs = [
        {
            'job_id': 101,
            'title': 'Python后端开发工程师',
            'company': '阿里巴巴',
            'location': '北京',
            'salary': '25000-35000',
            'description': '负责电商平台后端开发，要求熟悉Python、Django、MySQL',
            'match_score': 0.92,
            'source': 'ES'
        },
        {
            'job_id': 102,
            'title': 'Java开发工程师',
            'company': '腾讯',
            'location': '北京',
            'salary': '30000-40000',
            'description': '负责微服务开发，要求熟悉Java、Spring、Redis',
            'match_score': 0.88,
            'source': 'ES'
        },
        {
            'job_id': 103,
            'title': '前端开发工程师',
            'company': '字节跳动',
            'location': '北京',
            'salary': '22000-32000',
            'description': '负责前端开发，要求熟悉React、Vue、JavaScript',
            'match_score': 0.85,
            'source': 'ES'
        }
    ]
    
    # 基于技能过滤
    filtered_jobs = []
    user_skills_lower = [skill.lower() for skill in resume_analysis['skills']]
    
    for job in es_jobs:
        job_skills = job['description'].lower()
        matched_skills = sum(1 for skill in user_skills_lower if skill in job_skills)
        if matched_skills > 0:
            job['skill_match_count'] = matched_skills
            filtered_jobs.append(job)
    
    return filtered_jobs

def simulate_milvus_search(resume_analysis: Dict[str, Any]) -> list:
    """模拟Milvus语义检索"""
    
    # 基于语义相似度的模拟岗位
    milvus_jobs = [
        {
            'job_id': 201,
            'title': '大数据开发工程师',
            'company': '百度',
            'location': '北京',
            'salary': '28000-40000',
            'description': '负责大数据平台开发，Spark、Hadoop、数据处理',
            'match_score': 0.90,
            'source': 'Milvus'
        },
        {
            'job_id': 202,
            'title': '机器学习工程师',
            'company': '美团',
            'location': '北京',
            'salary': '32000-45000',
            'description': '负责推荐算法开发，Python、TensorFlow、深度学习',
            'match_score': 0.87,
            'source': 'Milvus'
        },
        {
            'job_id': 103,  # 重复ID用于测试去重
            'title': '前端开发工程师',
            'company': '字节跳动',
            'location': '北京',
            'salary': '22000-32000',
            'description': '负责前端开发，要求熟悉React、Vue、JavaScript',
            'match_score': 0.84,
            'source': 'Milvus'
        },
        {
            'job_id': 204,
            'title': 'DevOps工程师',
            'company': '京东',
            'location': '北京',
            'salary': '25000-35000',
            'description': '负责CI/CD和容器化，Docker、Kubernetes、云服务',
            'match_score': 0.82,
            'source': 'Milvus'
        }
    ]
    
    return milvus_jobs

def fuse_search_results(es_results: list, milvus_results: list, top_n: int) -> list:
    """融合搜索结果并去重"""
    
    # 合并结果
    all_results = es_results + milvus_results
    
    # 去重（基于job_id）
    seen_ids = set()
    unique_results = []
    
    for job in all_results:
        if job['job_id'] not in seen_ids:
            seen_ids.add(job['job_id'])
            unique_results.append(job)
        else:
            # 如果重复，选择分数更高的
            existing_job = next(j for j in unique_results if j['job_id'] == job['job_id'])
            if job['match_score'] > existing_job['match_score']:
                unique_results.remove(existing_job)
                job['source'] = 'Mixed'  # 标记为混合来源
                unique_results.append(job)
    
    # 按匹配分数排序
    unique_results.sort(key=lambda x: x['match_score'], reverse=True)
    
    # 返回Top N
    return unique_results[:top_n]

def generate_match_reason_mock(resume_analysis: Dict[str, Any], job: Dict[str, Any]) -> str:
    """模拟生成推荐理由"""
    
    user_skills = set(skill.lower() for skill in resume_analysis['skills'])
    job_desc_lower = job['description'].lower()
    
    # 找到匹配的技能
    matched_skills = [skill for skill in resume_analysis['skills'] 
                     if skill.lower() in job_desc_lower]
    
    # 生成推荐理由
    if matched_skills:
        skills_text = '、'.join(matched_skills[:3])
        reason = f"技能匹配度高：{skills_text}经验符合岗位需求"
    else:
        reason = "岗位与您的背景相关，建议关注"
    
    # 考虑经验年限
    if resume_analysis['experience_years'] >= 3:
        reason += f"，{resume_analysis['experience_years']}年工作经验匹配中高级岗位"
    
    # 考虑地点匹配
    if resume_analysis['location'] in job['location']:
        reason += "，工作地点匹配"
    
    return reason

def display_recommendation_result(api_response: Dict[str, Any]):
    """显示推荐结果"""
    
    if not api_response['success']:
        print(f"❌ 推荐失败: {api_response.get('message', '未知错误')}")
        return
    
    data = api_response['data']
    resume_info = data['resume_info']
    recommendations = data['job_recommendations']
    summary = data['recommendation_summary']
    
    print("\n" + "="*80)
    print("📋 RAG岗位推荐结果")
    print("="*80)
    
    # 简历信息
    print("👤 简历分析:")
    print(f"   📄 文件: {resume_info['file_name']}")
    print(f"   💼 经验: {resume_info['experience_years']} 年")
    print(f"   🎓 教育: {resume_info['education']}")
    print(f"   📍 地点: {resume_info['location']}")
    print(f"   🛠️ 技能: {', '.join(resume_info['skills'][:10])}")
    if len(resume_info['skills']) > 10:
        print(f"        等共 {len(resume_info['skills'])} 项技能...")
    
    # 推荐摘要
    print(f"\n📊 推荐摘要:")
    print(f"   🎯 推荐岗位: {summary['total_recommendations']} 个")
    print(f"   📈 平均匹配度: {summary['avg_match_score']:.1%}")
    print(f"   🔍 搜索方法: {', '.join(summary['search_methods_used'])}")
    print(f"   📝 ES结果: {summary['es_results_count']} 个")
    print(f"   🧠 Milvus结果: {summary['milvus_results_count']} 个")
    print(f"   🏆 匹配技能: {', '.join(summary['top_skills_matched'])}")
    
    # 推荐岗位
    print(f"\n🎯 推荐岗位详情:")
    
    for i, job in enumerate(recommendations, 1):
        print(f"\n   【{i}】 {job['title']}")
        print(f"       🏢 公司: {job['company']}")
        print(f"       📍 地点: {job['location']}")
        print(f"       💰 薪资: {job['salary']}")
        print(f"       📊 匹配度: {job['match_score']:.1%}")
        print(f"       🔍 来源: {job['source']}")
        print(f"       💡 推荐理由: {job['match_reason']}")
        
        # 职位描述
        desc = job['description']
        desc_preview = desc[:80] + '...' if len(desc) > 80 else desc
        print(f"       📝 职位描述: {desc_preview}")

def main():
    """主演示函数"""
    
    print("🚀 RAG岗位推荐API演示")
    print("基于简历内容的智能岗位匹配系统")
    print("="*80)
    
    # 示例简历内容
    sample_resume = """
李明简历

个人信息：
姓名：李明
工作经验：5年
教育背景：本科计算机科学与技术
期望地点：北京
期望薪资：25000-35000

核心技能：
- 编程语言：Python, Java, JavaScript
- 前端技术：React, Vue.js, HTML5, CSS3
- 后端框架：Django, Spring Boot, Express.js
- 数据库：MySQL, PostgreSQL, Redis, MongoDB
- 大数据：Spark, Hadoop, Kafka
- 云服务：AWS, Azure, Docker, Kubernetes
- 开发工具：Git, Jenkins, Maven

工作经历：
2019-2024 高级软件开发工程师 - 阿里巴巴
- 负责电商平台后端开发
- 参与微服务架构设计
- 优化系统性能，提升响应速度50%

项目经验：
1. 电商推荐系统 - Python, TensorFlow, Redis
2. 实时数据分析平台 - Spark, Kafka, Elasticsearch
3. 微服务治理平台 - Spring Boot, Kubernetes

自我评价：
5年全栈开发经验，熟悉大型分布式系统设计，
有丰富的电商和大数据项目经验。
"""
    
    # 执行RAG推荐
    result = simulate_resume_upload_and_recommend(sample_resume, top_n=8)
    
    # 显示结果
    display_recommendation_result(result)
    
    # 保存结果
    output_file = "rag_api_demo_result.json"
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(result, f, ensure_ascii=False, indent=2)
    
    print(f"\n💾 完整结果已保存到: {output_file}")
    
    print("\n" + "="*80)
    print("✅ RAG API演示完成!")
    print("📋 API响应格式:")
    print("   - success: 推荐是否成功")
    print("   - message: 处理结果描述")
    print("   - data.resume_info: 简历分析结果")
    print("   - data.job_recommendations: 推荐岗位列表")
    print("   - data.recommendation_summary: 推荐统计摘要")
    print("\n🔧 前端可以直接使用这个JSON格式进行展示!")

if __name__ == "__main__":
    main()
